<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
	<link rel="stylesheet" data-name="vs/editor/editor.main" href="../node_modules/monaco-editor/min/vs/editor/editor.main.css">
</head>
<body>

<h2>Monaco Editor Undo Redo Samples</h2>

<div style="padding: 5pt">
	<button id="undoButton" name="undo" onclick="undo();" disabled="true">Undo</button>
	<button id="redoButton" name="redo" onclick="redo();" disabled="true">Redo</button>
</div>

<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>

<script>var require = { paths: { 'vs': '../node_modules/monaco-editor/min/vs' } };</script>
<script src="../node_modules/monaco-editor/min/vs/loader.js"></script>
<script src="../node_modules/monaco-editor/min/vs/editor/editor.main.nls.js"></script>
<script src="../node_modules/monaco-editor/min/vs/editor/editor.main.js"></script>

<script>
	const value = [
		'define([], function() {',
		'\treturn ({p1, p2}) => {',
		'\t\treturn Promise.resolve("Hello, World");',
		'\t};',
		'});'
	].join('\n');

	const editor = monaco.editor.create(document.getElementById('container'), {
		value: [
			'function x() {',
			'\tconsole.log("Hello world!");',
			'}'
		].join('\n'),
		language: 'javascript'
	});

	editor.focus();
	editor.setPosition({ lineNumber: 2, column: 30 });

	const initialVersion = editor.getModel().getAlternativeVersionId();
	let currentVersion = initialVersion;
	let lastVersion = initialVersion;

	editor.onDidChangeModelContent(e => {
		const versionId = editor.getModel().getAlternativeVersionId();
		// undoing
		if (versionId < currentVersion) {
			enableRedoButton();
			// no more undo possible
			if (versionId === initialVersion) {
				disableUndoButton();
			}
		} else {
			// redoing
			if (versionId <= lastVersion) {
				// redoing the last change
				if (versionId == lastVersion) {
					disableRedoButton();
				}
			} else { // adding new change, disable redo when adding new changes
				disableRedoButton();
				if (currentVersion > lastVersion) {
					lastVersion = currentVersion;
				}
			}
			enableUndoButton();
		}
		currentVersion = versionId;
	});

	function undo() {
		editor.trigger('aaaa', 'undo', 'aaaa');
		editor.focus();
	}

	function redo() {
		editor.trigger('aaaa', 'redo', 'aaaa');
		editor.focus();
	}

	function enableUndoButton() {
		document.getElementById("undoButton").disabled = false;
	}

	function disableUndoButton() {
		document.getElementById("undoButton").disabled = true;
	}

	function enableRedoButton() {
		document.getElementById("redoButton").disabled = false;
	}

	function disableRedoButton() {
		document.getElementById("redoButton").disabled = true;
	}
</script>

</body>
</html>